package fdoj.eventInvitations.util;

import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class GoogleContacts {
	static String next = "localhost:8080/PozivNaDogadjaj/googlecontactsapi";
	static String scope = "https://www.google.com/m8/feeds/";
	static boolean secure = false;
	static boolean session = true;

	public static void printContacts() {
		String authSubLogin = AuthSubUtil.getRequestUrl(next, scope, secure,
				session);

		String token = AuthSubUtil.getTokenFromReply(authSubLogin);
		AuthSubUtil u = new AuthSubUtil();
		String sessionToken;
		try {
			sessionToken = AuthSubUtil.exchangeForSessionToken("http",
					"localhost", token, null);
			ContactsService myService = new ContactsService("fdoj-poziv-0.01");
			myService.setAuthSubToken(sessionToken, null);
			URL feedUrl = new URL(
					"https://www.google.com/m8/feeds/contacts/default/full");
			ContactFeed resultFeed = myService.getFeed(feedUrl,
					ContactFeed.class);
			for (ContactEntry entry : resultFeed.getEntries()) {
				System.out
						.println("-----------------------------------------------------------");
				if (entry.hasName()) {
					Name name = entry.getName();
					if (name.hasFullName()) {
						String fullNameToDisplay = name.getFullName()
								.getValue();
						if (name.getFullName().hasYomi()) {
							fullNameToDisplay += " ("
									+ name.getFullName().getYomi() + ")";
						}
						System.out.println("\t\t" + fullNameToDisplay);
					} else {
						System.out.println("\t\t (no full name found)");
					}
				}
				System.out.println("Email addresses:");
				for (Email email : entry.getEmailAddresses()) {
					System.out.print(" " + email.getAddress());
					if (email.getRel() != null) {
						System.out.print(" rel:" + email.getRel());
					}
					if (email.getLabel() != null) {
						System.out.print(" label:" + email.getLabel());
					}
					if (email.getPrimary()) {
						System.out.print(" (primary) ");
					}
					System.out.print("\n");
				}
				System.out
						.println("-----------------------------------------------------------");
			}
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (GeneralSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
